﻿using Microsoft.AspNetCore.Mvc;
using DataHelper;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Web;
using System.Drawing.Imaging;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml.Office2010.Excel;

namespace JKYGL.Controllers
{
    public class JKYController : Controller
    {
        public IActionResult page(string kd, string xm, string sfz, string gzdw, string kwzz)
        {

            System.Data.DataSet ds;
            if (kwzz != null)
            {
                if (kwzz == "其他考务人员")
                {
                    ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where  kd!='' " +
                        $"and not ( '主考，副主考，考务组长，监考甲，监考乙，监考丙，视频监考,巡考员,监考证' like  '%'+trim(kwzz)+'%') " +
                        $"order by gzdw,kd,kwzz");
                    ViewBag.dt = ds.Tables[0];
                    return View();
                }


                kwzz = kwzz.Replace("，", ",");
                if (kwzz.Split(",").Length > 1)
                {
                    ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where  '{kwzz}' like  '%'+trim(kwzz)+'%'  order by gzdw,kwzz,kd");
                }
                else
                {
                    if (gzdw != null)
                        ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where kwzz like '%{kwzz}%'  and gzdw like '%{gzdw}%' order by gzdw,kwzz,kd");
                    else
                        ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where kwzz like '%{kwzz}%' order by gzdw,kwzz,kd");
                }
                ViewBag.dt = ds.Tables[0];
                return View();
            }

            if (gzdw != null)
            {
                gzdw = gzdw.Replace("，", ",");
                if (gzdw.Split(",").Length > 1)
                {
                    ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where '{gzdw}' like '%'+trim(gzdw)+'%'" +
                           $"and not ( '主考，副主考，考务组长，监考甲，监考乙，监考丙，视频监考,巡考员,监考员' like  '%'+trim(kwzz)+'%') " +
                    $" order by gzdw");
                }
                else
                {

                    ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where gzdw='{gzdw}' and isnull(kwzz,'*')<>'*'" +
                            $"and not ( '主考，副主考，考务组长，监考甲，监考乙，监考丙，视频监考,巡考员,监考员' like  '%'+trim(kwzz)+'%') " +
                    $" order by gzdw");
                }
                ViewBag.dt = ds.Tables[0];
                return View();
            }


            if (sfz != null)
            {
                ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where sfz='{sfz}'");
                ViewBag.dt = ds.Tables[0];
                return View();
            }
            if (xm != null)
            {
                xm = xm.Replace("，", ",").Replace("\"", "").Replace("[", "").Replace("]", "");
                if (xm.Split(",").Length > 1)
                {
                    ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where '{xm}' like '%'+trim(xm)+'%'");
                }
                else
                {

                    ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where xm='{xm}'");
                }
                ViewBag.dt = ds.Tables[0];
                return View();
            }
            if (kd != null)
            {

                ds = SqlHelper.GetDataBySQL($"select xm,sfz,kd,kwzz,gzdw from jky where kd='{kd}' " +
                    $"and not ( '主考，副主考，考务组长，监考甲，监考乙，监考丙，视频监考,巡考员,监考证,监考员,巡考证' like  '%'+trim(kwzz)+'%') " +
                    $" order by gzdw");
                ViewBag.dt = ds.Tables[0];
            }

            return View();
        }
        [Route("print")]
        public IActionResult Print()
        {
            System.Data.DataSet kd;
            kd = SqlHelper.GetDataBySQL($"SELECT [DWDM],[DWMC]  FROM [SheKao].[dbo].[jkydw]  where iskd='是'");
            ViewBag.kd = kd.Tables[0];
            System.Data.DataSet dw;
            dw = SqlHelper.GetDataBySQL($"SELECT [DWDM],[DWMC]  FROM [SheKao].[dbo].[jkydw]  ");
            ViewBag.dw = dw.Tables[0];

            System.Data.DataSet kwzz;
            kwzz = SqlHelper.GetDataBySQL($"SELECT [kwzz],[color]  FROM [SheKao].[dbo].[kw]");
            ViewBag.kwzz = kwzz.Tables[0];


            return View();
        }
        public IActionResult getPic(string xmsfz)
        {

            Response.ContentType = "image/jpeg";

            Bitmap bm;

            try
            {
                bm = new Bitmap($@"D:\JKY\PIC\{xmsfz}.JPG");
            }
            catch
            {
                return null;
            }
            MemoryStream ms = new MemoryStream();
            bm.Save(ms, ImageFormat.Jpeg);
            bm.Dispose();
            return File(ms.ToArray(), "image/png");
        }

        /// <summary>
        /// 取Hash字符串
        /// </summary>
        /// <param name="sourceText">原文</param>
        /// <param name="toUpper">返回大写字符串</param>
        /// <returns>Hash字符串</returns>
        public static string ComputeHash(string sourceText, bool toUpper)
        {
            if (sourceText == null)
                return null;

            StringBuilder result = new StringBuilder();
            using (MD5 md5 = new MD5CryptoServiceProvider())
            {
                byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceText));
                if (toUpper)
                    for (int i = 0; i < data.Length; i++)
                        result.Append(data[i].ToString("X2"));
                else
                    for (int i = 0; i < data.Length; i++)
                        result.Append(data[i].ToString("x2"));
            }

            return result.ToString();
        }

        /// <summary>
        /// 取Hash字符串
        /// </summary>
        /// <param name="data">待加密数据字节结合</param>
        /// <param name="toUpper"></param>
        /// <returns></returns>
        public static string ComputeHash(byte[] data, bool toUpper)
        {
            if (data == null)
                return string.Empty;
            StringBuilder result = new StringBuilder();
            using (MD5 md5 = new MD5CryptoServiceProvider())
            {
                if (toUpper)
                    for (int i = 0; i < data.Length; i++)
                        result.Append(data[i].ToString("X2"));
                else
                    for (int i = 0; i < data.Length; i++)
                        result.Append(data[i].ToString("x2"));
            }

            return result.ToString();

        }

        public IActionResult GetPTQRCode(string url, int pixel = 3)
        {
            url = HttpUtility.UrlDecode(url);
            Response.ContentType = "image/jpeg";

            var bitmap = QRCoderHelper.GetPTQRCode(url, pixel);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            return File(ms.ToArray(), "image/png");
        }

        #region ZIP
        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="file">需要删除的文件路径</param>
        /// <returns></returns>
        public bool DeleteDir(string file)
        {
            try
            {
                //去除文件夹和子文件的只读属性
                //去除文件夹的只读属性
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
                //去除文件的只读属性
                System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
                //判断文件夹是否还存在
                if (Directory.Exists(file))
                {
                    foreach (string f in Directory.GetFileSystemEntries(file))
                    {
                        if (System.IO.File.Exists(f))
                        {
                            //如果有子文件删除文件
                            System.IO.File.Delete(f);
                            //Console.WriteLine(f);
                        }
                        else
                        {
                            //循环递归删除子文件夹
                            DeleteDir(f);
                        }
                    }
                    //删除空文件夹
                    Directory.Delete(file);
                }
                return true;
            }
            catch (Exception ex) // 异常处理
            {
                return false;
            }

        }
        /// <summary>
        /// 将指定文件压缩为Zip文件
        /// </summary>
        /// <param name="filePath">文件地址 D:/1.txt </param>
        /// <param name="zipPath">zip地址 D:/1.zip </param>
        public static void CompressFileZip(string filePath, string zipPath)
        {

            FileInfo fileInfo = new FileInfo(filePath);
            string dirPath = fileInfo.DirectoryName?.Replace("\\", "/") + "/";
            string tempPath = dirPath + Guid.NewGuid() + "_temp/";
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            fileInfo.CopyTo(tempPath + fileInfo.Name);
            try
            {
                if (System.IO.File.Exists(zipPath))
                    System.IO.File.Delete(zipPath);

                ZipFile.CreateFromDirectory(tempPath, zipPath);

            }
            catch
            { }
            DirectoryInfo directory = new(tempPath);
            if (directory.Exists)
            {
                //将文件夹属性设置为普通,如：只读文件夹设置为普通
                directory.Attributes = FileAttributes.Normal;

                directory.Delete(true);
            }
        }
        #endregion
        public IActionResult Index(string dw)
        {
            string oldid = HttpContext.Request.Cookies["GUID"];
            ViewBag.Id =oldid;
            if (oldid == null)
            {
                string id = Guid.NewGuid().ToString();
                CookieOptions options = new CookieOptions
                {
                    Expires = DateTime.Now.AddDays(7000)
                };
                HttpContext.Response.Cookies.Append("GUID", $"{id}", options);
                ViewBag.Id = id;
              
            }       

            ViewBag.ksmc = Program.ksmc;
            ViewBag.TraceIdentifier = ComputeHash(ViewBag.Id,false);
            //try
            //{
            //    ViewBag.TraceIdentifier = ComputeHash(HttpContext.Request.Headers["User-agent"][0], false);
            //}
            //catch
            //{
            //    ViewBag.TraceIdentifier = "CantGet!";
            //}
            string strsql = $"SELECT *  FROM [SheKao].[dbo].[jkydw] where dwdm='{dw}'";
            var ds0 = SqlHelper.GetDataBySQL(strsql);
            System.Data.DataTable dt = ds0.Tables[0];
            if(dt.Rows.Count==1)
                ViewBag.gzdw = dt.Rows[0]["DWMC"].ToString();
            else
                ViewBag.gzdw = "";

           // if (dw == "410811301") ViewBag.gzdw = "濮阳县一中";
           // if (dw == "410811303") ViewBag.gzdw = "濮阳县三中";
           // if (dw == "410811000") ViewBag.gzdw = "濮阳县教育局";
           // if (dw == "410811304") ViewBag.gzdw = "兴濮中学";
           // if (dw == "410811305") ViewBag.gzdw = "濮阳县职教中心";
           // if (dw == "410811308") ViewBag.gzdw = "建业国际学校";
           // if (dw == "410811309") ViewBag.gzdw = "实验高中";
           // if (dw == "410811302") ViewBag.gzdw = "濮阳县职业技术学校";
           //// if (dw == "410811307") ViewBag.gzdw = "职业技术学院附中";
           // if (dw == "410811202") ViewBag.gzdw = "濮阳县二中";
            // if (dw == "410811307") ViewBag.gzdw = "职业技术学院附中";
            string sqlstr = $"select * from jky where  TraceIdentifier='{ViewBag.TraceIdentifier}'";
            var ds = SqlHelper.GetDataBySQL(sqlstr);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ViewBag.gzdw= ds.Tables[0].Rows[0]["GZDW"].ToString().Trim();
                ViewBag.xm = ds.Tables[0].Rows[0]["xm"].ToString().Trim();
                ViewBag.sjh = ds.Tables[0].Rows[0]["sjh"].ToString().Trim();
                ViewBag.sfz = ds.Tables[0].Rows[0]["sfz"].ToString().Trim();
                ViewBag.yhkh = ds.Tables[0].Rows[0]["yhkh"].ToString().Trim();
                ViewBag.khh = ds.Tables[0].Rows[0]["khh"].ToString().Trim();
                return View();
            }

            return View();
        }
        public IActionResult Admin(string dw, string msg, string kd)
        {
            ViewBag.ksmc = Program.ksmc;
            if (dw == "0811")
            {
                string strsql2 = $"SELECT *  FROM [SheKao].[dbo].[jkydw] ";
                var ds2 = SqlHelper.GetDataBySQL(strsql2);
                System.Data.DataTable dt2 = ds2.Tables[0];
                List<string> dws=new List<string>() ;
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    dws.Add($"{dt2.Rows[i]["dwdm"].ToString().Trim()}:{dt2.Rows[i]["dwMC"].ToString().Trim()}");
                }
                
                ViewBag.dws = dws.ToArray();
                return View("dwlist");
            }

            System.Data.DataSet ds;
            if (kd == null)
                kd = "";
            if (kd.Length > 0)
            {
                string strsqlkd = $"select * from jky where kd='{kd}' order by kwzz";
                ds = SqlHelper.GetDataBySQL(strsqlkd);
                ViewBag.dt = ds.Tables[0];
                ViewBag.gzdw = "";
                return View();
            }


            if (msg == null)
                msg = "";
            ViewBag.msg = msg;

            if (dw == null)
                dw = "";
            ViewBag.dw = dw;

            string strsqlkw = "select kwzz from [SheKao].[dbo].[kw]";
            var dskw=SqlHelper.GetDataBySQL(strsqlkw);
            System.Data.DataTable dtkw = dskw.Tables[0];
            if (dtkw.Rows.Count > 0)
                ViewBag.kwzzs = dtkw;
            else
                ViewBag.kwzzs =null;




            string strsql1 = $"SELECT *  FROM [SheKao].[dbo].[jkydw] where dwdm='{dw}'";
            var ds0 = SqlHelper.GetDataBySQL(strsql1);
            System.Data.DataTable dt = ds0.Tables[0];
            if (dt.Rows.Count == 1)
                ViewBag.gzdw = dt.Rows[0]["DWMC"].ToString();
            else
            {
               //ViewBag.gzdw = "错误";
               return View("Error");
            }
            //if (dw == "410811301") ViewBag.gzdw = "濮阳县一中";
            //if (dw == "410811303") ViewBag.gzdw = "濮阳县三中";
            //if (dw == "410811000") ViewBag.gzdw = "濮阳县教育局";
            //if (dw == "410811304") ViewBag.gzdw = "兴濮中学";
            //if (dw == "410811305") ViewBag.gzdw = "濮阳县职教中心";
            //if (dw == "410811308") ViewBag.gzdw = "建业国际学校";
            //if (dw == "410811309") ViewBag.gzdw = "实验高中";
            //if (dw == "410811302") ViewBag.gzdw = "濮阳县职业技术学校";
        //    if (dw == "410811307") ViewBag.gzdw = "学院附中";

            string strsql = $"select * from jky where gzdw='{ViewBag.gzdw}'";
            if (dw == "410811999")
            {
                ViewBag.gzdw = "招生考试中心";
                strsql = $"select * from jky";
            }
            if (dw == "410811000")
            {
                ViewBag.gzdw = "招生考试中心A";
                strsql = "select * from DaoCHU";
            }



            ds = SqlHelper.GetDataBySQL(strsql);
            ViewBag.dt = ds.Tables[0];

            return View();
        }

        public IActionResult cancelFG(string dw, string gzdw, string token)
        {


            gzdw = HttpUtility.UrlDecode(gzdw);
            if (token == "3255701")
            {
                string sqlstr = $"update jky set KWZZ= '',KD= ''  where gzdw='{gzdw}'";
                if (gzdw == "招生考试中心A")
                { sqlstr = $"update jky set KWZZ= '',KD= ''"; }

                var re = SqlHelper.ExecuteNonQueryBySQL(sqlstr);
                ViewBag.msg = "已取消完成。";
                ViewBag.dw = dw;
                ViewBag.gzdw = gzdw;
                string strsql = $"select * from jky where gzdw='{ViewBag.gzdw}'";
                if (dw == "410811999")
                {
                    ViewBag.gzdw = "招生考试中心";
                    strsql = $"select * from jky";
                }
                var ds = SqlHelper.GetDataBySQL(strsql);
                ViewBag.dt = ds.Tables[0];
                return View("admin");
            }
            else
            {
                ViewBag.msg = "认证失败，操作被拒绝。";
                ViewBag.dw = dw;
                ViewBag.gzdw = gzdw;
                string strsql = $"select * from jky where gzdw='{ViewBag.gzdw}'";
                if (dw == "410811999")
                {
                    ViewBag.gzdw = "招生考试中心";
                    strsql = $"select * from jky";
                }
                var ds = SqlHelper.GetDataBySQL(strsql);
                ViewBag.dt = ds.Tables[0];
                return View("admin");
            }


        }

        public string QXJKY(string xmsfz)  //保存监考员分工
        {
            string sqlstr = $"delete  from jky where   trim(xm)+sfz='{xmsfz}'";
            int re = 0;
            try
            {
                re = SqlHelper.ExecuteNonQueryBySQL(sqlstr);
            }
            catch
            { }

            if (re == 1)
                return "操作成功";
            else
                return "操作失败";
        }

        public string QXJKYFG(string sfz)  //保存监考员分工
        {
            string sqlstr = $"update jky set KWZZ= '',KD= ''  where sfz='{sfz}'";
            int re = 0;
            try
            {
                re = SqlHelper.ExecuteNonQueryBySQL(sqlstr);
            }
            catch
            { }

            if (re == 1)
                return "操作成功";
            else
                return "操作失败";
        }
        public string saveJKYFG(string sfz, string zd, string val)  //保存监考员分工
        {
            if(sfz==null||zd==null||val==null) return "操作失败";

            System.Diagnostics.Debug.WriteLine("输出");

            string sqlstr = $"update jky set {zd}='{val}' where sfz='{sfz}'";
            int re = 0;
            try
            {
                re = SqlHelper.ExecuteNonQueryBySQL(sqlstr);
            }
            catch
            { }

            if (re == 1)
                return "已记录";
            else
                return "操作失败";
        }
        public IActionResult exportPic(string dw, string dwmc)
        {
            string dataFileName = $@"D:\JKY\{dw}PIC.zip";
            if (System.IO.File.Exists(dataFileName))
            {
                return File(new FileStream(dataFileName, FileMode.Open), "application/x-zip-compressed");

            }
            ViewBag.msg = "没有准备好照片数据，请先执行导出数据！";
            return View("Err");


        }
        public IActionResult exportData(string dw, string dwmc)
        {
            if (dw == null || dwmc == null)
                return View("Err");
            string strsql = $"select '{dw}'+dbo.padleft(row_number() over(order by kwzz desc),0,3) as jkbh,xm,sfz,sjh,gzdw,kwzz,kd,yhkh,khh from jky where gzdw='{dwmc}'";
            if (dw == "410811000")
                strsql = "select * from DaoCHU";
            var ds = SqlHelper.GetDataBySQL(strsql);
            System.Data.DataTable dt = ds.Tables[0];

            string bakfilenameid = Guid.NewGuid().ToString();
            ExeclHelper.ExportExcelFile($@"D:\JKY\{dw}.XLSX", dt);
            if (dw != "410811000")
            {
                //准备PIC
                if (System.IO.Directory.Exists(@$"D:\JKY\{dw}\"))
                { DeleteDir(@$"D:\JKY\{dw}\"); }
                if (System.IO.File.Exists(@$"D:\JKY\{dw}PIC.zip"))
                { System.IO.File.Delete(@$"D:\JKY\{dw}PIC.zip"); }

                System.IO.Directory.CreateDirectory(@$"D:\JKY\{dw}\");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    try
                    {
                        System.IO.File.Copy($@"D:\JKY\PIC\{dt.Rows[i]["xm"].ToString().Trim()}{dt.Rows[i]["sfz"].ToString().Trim()}.JPG", @$"D:\JKY\{dw}\{dt.Rows[i]["sfz"]}.JPG");
                    }
                    catch
                    { }
                }
                ZipFile.CreateFromDirectory($@"D:\JKY\{dw}\", $@"D:\JKY\{dw}PIC.zip");
            }
            else
            {          //准备PIC
                if (System.IO.Directory.Exists(@$"D:\JKY\{dw}\"))
                { DeleteDir(@$"D:\JKY\{dw}\"); }
                if (System.IO.File.Exists(@$"D:\JKY\{dw}PIC.zip"))
                { System.IO.File.Delete(@$"D:\JKY\{dw}PIC.zip"); }

                System.IO.Directory.CreateDirectory(@$"D:\JKY\{dw}\");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    try
                    {
                        System.IO.File.Copy($@"D:\JKY\PIC\{dt.Rows[i]["xm"].ToString().Trim()}{dt.Rows[i]["sfz"].ToString().Trim()}.JPG", @$"D:\JKY\{dw}\{dt.Rows[i]["sfz"]}.JPG");
                    }
                    catch
                    { }
                }
                ZipFile.CreateFromDirectory($@"D:\JKY\{dw}\", $@"D:\JKY\{dw}PIC.zip");

            }
            // CompressFileZip($@"D:\JKY\{dw}\", $@"D:\JKY\{dw}.zip");
            string filePath = $@"D:\JKY\Tmp\{bakfilenameid}.zip";

            if (!System.IO.Directory.Exists(@$"D:\JKY\Tmp\")) System.IO.Directory.CreateDirectory("D:\\JKY\\Tmp");
            CompressFileZip($@"D:\JKY\{dw}.XLSX", filePath);

            // CompressFileZip($@"D:\JKY\{dw}\*.*",filePath1);

            return File(new FileStream(filePath, FileMode.Open), "application/x-zip-compressed");


        }
        static bool IsValidChineseName(string name)
        {   if (name == null) return false;    
            // 使用正则表达式检查姓名是否符合规则，有效返回True
            return Regex.IsMatch(name, @"^[\u4e00-\u9fa5]{2,}$");
        }
        static bool IsValidPhoneNumber(string phoneNumber)
        {if (phoneNumber == null) return false;
            // 使用正则表达式检查手机号是否符合规则
            return Regex.IsMatch(phoneNumber, @"^1[3456789]\d{9}$");
        }
        public string saveJKY(string gzdw, string xm, string sfz, string sjh, string khh, string yhkh, string imgBase64, string TraceIdentifier)
        {
         
            if (!IsValidChineseName(xm)) return "姓名至少两个汉字,不能包含空格或非中文\r\n请核对姓名后重新提交";
            if(sjh==null) return "手机机号填写不合规\r\n请核对手机号后重新提交"; 
            else sjh =sjh.Trim().Replace(" ","");
            if(!IsValidPhoneNumber(sjh)) return "手机机号填写不合规\r\n请核对手机号后重新提交";
            if (!CheckIDCard18(sfz)) return "身份证校验失败\r\n请核对身份证后重新提交";
            if (yhkh?.Length > 0 && !CheckBankCardNo(yhkh)) return "银行卡校验失败\r\n请核对银行卡后重新提交";
            if (imgBase64 == null) return "照片保存失败\r\n请重新提交";
            if (imgBase64.Length < 20000) return "照片保存失败\r\n请重新提交";
            try
            {
                //string d = System.Web.HttpUtility.UrlEncode(c); URL编码
                imgBase64 = System.Web.HttpUtility.UrlDecode(imgBase64).Split(',')[1];
                byte[] arr = Convert.FromBase64String(imgBase64);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                if (JKYGL.OpenCvSharpHelper.isHaveFace(bmp))
                {
                 //   bmp.Save($"D:\\JKY\\PIC\\{xm + sfz}.JPG", System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                else
                {
                    return "照片合规检查失败，未找到人脸\r\n请重新提交";
                }

            }
            catch
            {
                return "照片保存失败\r\n请重新提交";
            }
            //先检查有无数据，如果有的话进行更新，如果没有，添加 依据 xm+SFZ
            string sqlstr = $"select * from jky where xm='{xm}' and sfz='{sfz}'";
            var ds = SqlHelper.GetDataBySQL(sqlstr);
            if (ds.Tables[0].Rows.Count > 0)
            {//存在记录
                if (ds.Tables[0].Rows[0]["kwzz"].ToString() == "")
                {
                    sqlstr = $"delete from jky where xm='{xm}' and sfz='{sfz}'";
                    SqlHelper.ExecuteNonQueryBySQL(sqlstr);

                    if (savetosql(gzdw, xm, sfz, sjh, khh, yhkh, imgBase64, TraceIdentifier) == 1)
                    {
                        try
                        {
                            //string d = System.Web.HttpUtility.UrlEncode(c); URL编码
                         //   imgBase64 = System.Web.HttpUtility.UrlDecode(imgBase64).Split(',')[1];
                            byte[] arr = Convert.FromBase64String(imgBase64);
                            MemoryStream ms = new MemoryStream(arr);
                            Bitmap bmp = new Bitmap(ms);
                            if (JKYGL.OpenCvSharpHelper.isHaveFace(bmp))
                            {
                                   bmp.Save($"D:\\JKY\\PIC\\{xm + sfz}.JPG", System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                            else
                            {
                                return "照片合规检查失败，未找到人脸\r\n请重新提交";
                            }

                        }
                        catch
                        {
                            return "照片保存失败\r\n请重新提交";
                        }
                        return "保存完成";
                    }
                    else
                        return "保存失败";
                }
                else
                {
                    return "已分配考务工作，如需更新信息请联系本校管理员。";
                }

            }
            else
            {
                if (savetosql(gzdw, xm, sfz, sjh, khh, yhkh, imgBase64, TraceIdentifier) == 1)
                    return "保存完成";
                else
                    return "保存失败";
            }
            // return imgBase64;

        }
        public int savetosql(string gzdw, string xm, string sfz, string sjh, string khh, string yhkh, string imgBase64, string TraceIdentifier)
        {
            string sqlstr = "INSERT INTO [dbo].[JKY]([XM],[SJH],[SFZ],[GZDW],[PICPath],[YHKH],[KHH],[TraceIdentifier])" +
                    $@" VALUES('{xm}','{sjh}','{sfz}','{gzdw}','D:\JKY\{xm + sfz}.JPG','{yhkh}','{khh}','{TraceIdentifier}')";
            int re = 0;
            try
            {
                re = SqlHelper.ExecuteNonQueryBySQL(sqlstr);
            }
            catch
            { }
            return re;
        }

        //检查身份证
        public static bool CheckIDCard18(string IDCard)
        {
            //18位身份证号由6位的地区代码、8位的生日码、3位编号和1位的校验码组成。
            if (string.IsNullOrWhiteSpace(IDCard) || IDCard.Length != 18)
                return false;
            long n = 0;
            if (long.TryParse(IDCard.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(IDCard.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证  
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(IDCard.Remove(2)) == -1)
            {
                return false;//省份验证  
            }
            string birth = IDCard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = IDCard.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != IDCard.Substring(17, 1).ToLower())
            {
                return false;//校验码验证  
            }
            return true;//符合GB11643-1999标准  
        }

        //检查银行卡
        public static bool CheckBankCardNo(string no)
        {
            if (no == null || no.Length == 0) return false;
            //第⼀步：从右边第1个数字开始每隔⼀位乘以2；
            //第⼆步：把在第⼀步中获得的乘积的各位数字相加，然后再与原号码中未乘2的各位数字相加；
            //第三步：对于第⼆步求和值中个位数求10的补数，如果个位数为0则该校验码为0。
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^\d{7,19}$"); if (!regex.IsMatch(no)) return false;
            var temp = no;
            var temp0 = temp.ToCharArray().Reverse().ToArray();
            var sum = 0d;
            for (int i = 1, len = temp0.Length; i < len; i++)
            {
                var temp1 = Convert.ToInt16(temp0[i].ToString());
                if ((i + 1) % 2 == 0)
                {
                    temp1 *= 2;
                }
                sum += Math.Floor(temp1 / 10d) + (temp1 % 10);
            }
            var checkCode = 10 - sum % 10;
            checkCode = checkCode == 10 ? 0 : checkCode;   //Add By Smily 解决最后一位是0的BUG
            return temp0[0].ToString() == checkCode.ToString("0");
        }
       
    }
}
